package cn.com.open.itembank.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;


public class ThreadPoolConfig implements AsyncConfigurer{

    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolConfig.class);


    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        //当前线程数
        threadPool.setCorePoolSize(30);
        //最大线程数
        threadPool.setMaxPoolSize(200);
        //线程池所使用的缓冲队列
        threadPool.setQueueCapacity(50);
        //设置当pool已经达到max size的时候,如何处理新任务
        //CallerRuns 表示不再新线程中执行任务,而是在调用者所在的线程来执行
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //等待任务在关机时完成--表明等待所有线程执行完
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        //等待时间 （默认为0，此时立即停止），并没等待xx秒后强制停止
        threadPool.setAwaitTerminationSeconds(30);
        //线程名称前缀(自定义线程池)
        threadPool.setThreadNamePrefix("CustomizeAsyncThreadPool-");
        //初始化
        threadPool.initialize();
        return threadPool;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new MyAsyncExceptionHandler();
    }
}
